--- 模块功能：GPIO功能测试.
-- @author miuser
-- @module elderphone.uart
-- @license MIT
-- @copyright miuser
-- @release 2020-05-15

require"pins"
module(...,package.seeall)

-------------------------------------------- 配置串口 --------------------------------------------
-- 串口ID,串口读缓冲区
local UART_ID, sendQueue= 129, {}
-- 串口超时，串口准备好后发布的消息
local uartimeout= 25
--保持系统处于唤醒状态，不会休眠
pm.wake("mcuart")
uart.setup(UART_ID, 115200, 8, uart.PAR_NONE, uart.STOP_1, nil, 1)

uart.on(UART_ID, "receive", function(uid)
    table.insert(sendQueue, uart.read(uid, 8192))
    sys.timerStart(sys.publish, uartimeout, "UART_RECV_ID")
end)



local function write( str)
    --软串口
    uart.write(UART_ID, str)
end

-- 向串口发送收到的字符串
sys.subscribe("UART_RECV_ID", function()
    local str = table.concat(sendQueue)
    -- 串口的数据读完后清空缓冲区
    local splitlist = {}
    string.gsub(str, '[^,]+', function(w) table.insert(splitlist, w) end)
    local count=table.getn(splitlist)
    sys.publish("UARTIN",str)
    if (count==1) then
        log.info("sys.publish",splitlist[1])
        sys.publish(splitlist[1])
    elseif count==2 then
        sys.publish(splitlist[1],splitlist[2])
    elseif count==3 then
        sys.publish(splitlist[1],splitlist[2],splitlist[3])
    end

    sendQueue = {}
    log.info("uart read length:", #str,"Port"..UART_ID)
    write(str.."->OK".."\n\r")
    
end)

local function uartrsv(msg)
    uart.write(UART_ID,common.utf8ToGb2312(msg).."\n\r")
end
sys.subscribe("UARTOUT", uartrsv)